﻿'use strict';

QuotingToolApp
    .controller('SearchContractsController', ['$scope', '$location', '$routeParams', '$uibModal', 'contractsData', 'notifications', 'CommonServices',
        function ($scope, $location, $routeParams, $uibModal, contractsData, notifications, CommonServices) {

        var self = this;
        var selectedAccount;
        var selectedCustomer;

        self.init = function () {

            //initialize contracts collection based on parameter or empty for a new wizard
            if (CommonServices.newQuoteParamsObj.ContractIDs)
                self.contractsCollection = CommonServices.newQuoteParamsObj.ContractIDs;
            else
                self.contractsCollection = [];

            //self.autoCompleteAccountsColl = [];
            //self.autoCompleteCustomersColl = [];

            //initialize search by field
            self.searchByApp = {
                options: [
                  { id: '1', appName: 'SFDC' },
                  { id: '2', appName: 'Oracle' }
                ]               
            };
            self.searchByApp.selectedOption = self.searchByApp.options[0];

            //load top divisions field options
            self.topDivisions = [];
            CommonServices.getTopDivisions()
                       .$promise
                       .then(function (results) {
                           self.topDivisions = results;

                       })
                       .catch(function (response) { notifications.showError("Top divisions load failed"); }
                   );

            //load top region field options
            self.topRegions = [];
            CommonServices.getTopRegions()
                       .$promise
                       .then(function (results) {
                           self.topRegions = results;

                       })
                       .catch(function (response) { notifications.showError("Top regions load failed"); }
                   );

            //retrieve default account details by opportunity id from url parameters if exists
            //if ($location.search()["oppid"])
            if ($routeParams.oppid) {
                //contractsData.getOpportunity($location.search()["oppid"])
                CommonServices.getOpportunity($routeParams.oppid)
                       .$promise
                       .then(function (results) {                           
                           self.selectedAccount = CommonServices.selectedAccountParam = results;

                           self.topDivisions.selectedOption =
                               self.topDivisions[self.topDivisions.findIndex(function (element, index, array) { return element.TopDivisionName === this }, results.TopDivision)];                           
                       })
                       .catch(function (response) { notifications.showError("Opportunity load failed"); }
                   );
            }

            //initialize search filters field options
            self.searchFilters = [
                { FilterName: 'All', FilterValue: 'A', checked: true },
                { FilterName: 'Bill To', FilterValue: 'B', checked: false },
                { FilterName: 'Sold To', FilterValue: 'S', checked: false },
                { FilterName: 'Installed At', FilterValue: 'E', checked: false }
            ];

            //initialize exp. perion field options and set default value
            self.expirationPeriod = {
                options: [
                  { id: '3', name: '3 months' },
                  { id: '6', name: '6 months' },
                  { id: '9', name: '9 months' },
                  { id: '12', name: '12 months' },
                  { id: '18', name: '18 months' },
                  { id: '24', name: '24 months' },
                  { id: '36', name: '36 months' }
                ]               
            };
            self.expirationPeriod.selectedOption = self.expirationPeriod.options[1];
            
            self.includeWarranty = { FilterName: 'Include warranty only contracts', FilterValue: 'W', checked: false };


            self.addContracts = {
                options:
                [
                   { name: 'Contract Num', value: '1' },
                   { name: 'Order Num', value: '2' },
                   { name: 'Serial Num', value: '3' },
                   { name: 'PO Num', value: '4' }
                ],
                selectedOption: '2'
            };
            
            //initialize right click menu
            self.menuOptions = [
                [
                    function ($itemScope) {
                        if ($itemScope.row.isLead == true)
                            return 'Uncheck lead contract';
                        else
                            return 'Check as lead contract';
                    },
                    function ($itemScope) {
                        var resetFlag = false;

                        if ($itemScope.row.isLead == true) {
                            resetFlag = true;
                            self.leadContract = null;
                        }

                        //reset rows that previously marked as lead contract
                        self.contractsCollection.forEach(function (element) {
                            if (element.isLead) element.isLead = false;
                        });

                        //mark selected row as lead contract if 'Check operation selected
                        if (!resetFlag) {
                            $itemScope.row.isLead = true;
                            self.leadContract = $itemScope.row.ID;
                        }
                    }
                ],
                 null, // Dividier
                  ['Remove contract', function ($itemScope) {
                      self.removeItem($itemScope.row);
                  }]
            ];                  
            
            //define default visible tab for search contracts table
            self.currentTab = 1;

            //visual styling of buttons
            angular.element('.pull-down').each(function () {
                var $this = $(this);
                $this.css('margin-top', $this.parent().height() - $this.height() - 100)
            });
        };

        self.getters = {
            START_DATE: function (row) {
                return new Date(row.START_DATE);
            },
            END_DATE: function (row) {
                return new Date(row.END_DATE);
            },
            ESTIMATED_AMOUNT: function (row) {
                return parseFloat(row.ESTIMATED_AMOUNT);
            }
        }

            //**********************MENU DEFINITION AND MENU FUNCTIONS ***********************************************************

        //self.getMenuTitle = function ($itemScope, menuType) {
        //    switch(menuType){

        //        case 1:
        //            if ($itemScope.row.isLead == true)
        //                return 'Uncheck lead contract';
        //            else
        //                return 'Check as lead contract';                   

        //        case 2:
        //            return 'Remove contract';
        //    }
        //};
        
        //self.doMenu = function ($itemScope, menuType) {
        //    switch (menuType) {
        //        case 1:
        //            self.setAsLeadContract($itemScope.row);
        //            break;

        //        case 2:
        //            self.removeItem($itemScope.row);
        //            break;
        //    }

        //};

        //self.setAsLeadContract = function (row) {
        //    //detect operation type - check or uncheck

        //    var resetFlag = false;
        //    if (row.isLead == true) {
        //        resetFlag = true;
        //        self.leadContract = null;
        //    }

        //    //reset rows that previously marked as lead contract
        //    self.contractsCollection.forEach(function (element) {
        //        if (element.isLead) element.isLead = false;
        //    });

        //    //mark selected row as lead contract if 'Check operation selected
        //    if (!resetFlag) {
        //        row.isLead = true;
        //        self.leadContract = row.ID;
        //    }

        //};

        //********************** Search Data functions ***********************************************************

        self.getAccounts = function (query) {

            if (query) {

                return CommonServices.getAccounts(query)
                    .$promise
                    .then(function (results) {
                        //return results.slice(0, 15);
                        return results;

                    })
                    .catch(function (response) {
                        console.log(response);
                    }
                );
            }
            else {
                return null;
            }
        }

        self.getCustomers = function (query) {

            if (query) {

                return CommonServices.getCustomers(query)
                    .$promise
                    .then(function (results) {
                        //return results.slice(0, 15);
                        return results;

                    })
                    .catch(function (response) {
                        console.log(response);
                    }
                );
            }
            else {
                return null;
            }
        }
        //self.searchAccounts = function (query) {           

        //    if (query) {

        //        CommonServices.getAccounts(query)
        //            .$promise
        //            .then(function (results) {
        //                self.autoCompleteAccountsColl = results;
        //                if (results.length > 0)
        //                    angular.element("#sfdcAccountOptions").show();

        //            })
        //            .catch(function (response) {
        //                console.log(response);
        //                angular.element("#sfdcAccountOptions").hide();
        //            }
        //        );

        //    }
        //    else {
        //        self.autoCompleteAccountsColl = null;
        //        angular.element("#sfdcAccountOptions").hide();
        //    }            

        //};

        //self.searchCustomers = function (query) {

        //    if (query) {

        //        contractsData.getCustomers(query)
        //            .$promise
        //            .then(function (results) {
        //                self.autoCompleteCustomersColl = results;
        //                if (results.length > 0)
        //                    angular.element("#oracleCustomerOptions").show();
        //            })
        //            .catch(function (response) {
        //                console.log(response);
        //                angular.element("#oracleCustomerOptions").hide();
        //            }
        //        );

        //    }
        //    else {
        //        self.autoCompleteCustomersColl = null;
        //        angular.element("#oracleCustomerOptions").hide();
        //    }

        //};

        //self.setSelected = function (_selected) {

        //    if (_selected.CustomerID) {
        //        self.selectedCustomer = _selected;
        //        angular.element("#oracleCustomerOptions").hide();               
        //    }
        //    else {
        //        if (_selected.MasterAccountID) {
        //            self.selectedAccount = CommonServices.selectedAccountParam = _selected;
        //        }
        //        else
        //            //alert("No MA is linked to the account please search according to Oracle account name");
        //            notifications.showWarning({ message: 'No MA is linked to the account. Please search according to Oracle account name' });

        //        angular.element("#sfdcAccountOptions").hide();
        //    }          
        //};

        self.fieldsReset = function () {

            if (self.searchByApp.selectedOption.id == '1')
                self.selectedAccount = null;
            else if (self.searchByApp.selectedOption.id == '2')
                self.selectedCustomer = null;

            self.searchFilters[0].checked = true;
            self.expirationPeriod.selectedOption = self.expirationPeriod.options[1];
            self.includeWarranty.checked = false;
            self.topDivisions.selectedOption = "";
        };

        self.customerRelationChange = function (FilterValue, state) {

            if (state == true)
                if (FilterValue != 'A')            //disable 'All' filter if any other filter selected
                {
                    if (self.searchFilters[0].checked)
                        self.searchFilters[0].checked = false;
                }
                else                               //disable other filters if 'All' filter selected
                    for (var i = 1; i < self.searchFilters.length; i++) {
                        self.searchFilters[i].checked = false;
                    }

        };

        self.searchContracts = function (searchcontractsform) {
            if (searchcontractsform.$valid) {
                //initilize search parameters object
                var searchParams = {
                    CustomerID: 'null',
                    MasterAccountID: 'null',
                    filters: null,
                    expPeriod: 6,       //set default value for expiration period                
                    warranty: 'N',      //set default value for warranty included field
                    topDivisionId: 'null',
                    topRegionId: 'null'
                };

                if (self.searchByApp.selectedOption.id == '1' && self.selectedAccount) searchParams.MasterAccountID = self.selectedAccount.MasterAccountID;
                if (self.searchByApp.selectedOption.id == '2' && self.selectedCustomer) searchParams.CustomerID = self.selectedCustomer.CustomerID;
                if (self.topDivisions.selectedOption) searchParams.topDivisionId = self.topDivisions.selectedOption.TopDivisionID;
                if (self.topRegions.selectedOption) searchParams.topRegionId = self.topRegions.selectedOption.TopRegionCode;
                if (self.expirationPeriod.selectedOption) searchParams.expPeriod = self.expirationPeriod.selectedOption.id;
                if (self.includeWarranty.checked) searchParams.warranty = 'Y';

                for (var i = 0; i < self.searchFilters.length; i++) {
                    if (self.searchFilters[i].checked)

                        if (searchParams.filters == null)
                            searchParams.filters = self.searchFilters[i].FilterValue;
                        else
                            searchParams.filters += self.searchFilters[i].FilterValue;
                }

                contractsData.getContracts(searchParams)
                       .$promise
                       .then(function (results) {

                           if (results != null) {
                                   self.displayContractsCollection = results;
                               self.addContractsSearchResults(results);
                           }
                           else {
                               notifications.showWarning('Contracts not found');
                           }
                       })
                       .catch(function (response) {
                           notifications.showError('Error searching contracts');
                           console.log(response);
                       }
                   );
            }
        };

        self.searchAdditionalContracts = function (additionacontractsform) {

            if (additionacontractsform.$valid) {

                //initilize search parameters object
                var searchParams = {
                    searchBy: self.addContracts.selectedOption,
                    searchText: self.addContracts.searchText
                };

                contractsData.getAdditionalContracts(searchParams)
                       .$promise
                       .then(function (results) {

                           if (results != null) {
                               self.addContractsSearchResults(results);
                           }
                           else {
                               notifications.showWarning('Contracts not found');
                           }

                       })
                       .catch(function (response) {
                           notifications.showError('Error searching contracts');
                           console.log(response);
                       }
                   );
            }
        };

        self.addContractsSearchResults = function (results) {
            //function is used to add contracts results to the list of existing contracts and prevent duplicates in the list
            var msgText = "";
            var isWarning = false;
            var duplicates = [];

            if (self.contractsCollection.length > 0) {           //contracts collection already populated with previous data - prevent duplicates

                //reset rows that previously marked as new
                self.contractsCollection.forEach(function (element) {
                    if (element.isNew) element.isNew = false;
                });


                for (var i = 0; i < results.length; i++) {
                    if (self.contractsCollection.findIndex(function (element, index, array) { return this.CONTRACT_NUMBER === element.CONTRACT_NUMBER }, results[i]) == -1) {
                        results[i].isNew = true;
                        self.contractsCollection.unshift(results[i]);
                    }
                    else {
                        duplicates.push(results[i].CONTRACT_NUMBER);
                        isWarning = true;
                    }
                }

                msgText += (results.length - duplicates.length) + " contracts found. ";
                if (isWarning) {
                    msgText += ((duplicates.length == 1) ? "Contract " : "Contracts ") + duplicates.toString() + " already exist in the table.";
                    notifications.showWarning(msgText);
                }
                else
                    notifications.showSuccess(msgText);
            }

            else {                    //contracts collection is empty - show found results as is
                self.contractsCollection = results;
                notifications.showSuccess(results.length + " " + ((results.length == 1) ? "contract" : "contracts") + " found.");
            }

            CommonServices.contractsCollectionParam = self.contractsCollection;
        };

        self.goNext = function () {
            var currencyCodes = [];           

           // self.contractsCollection.forEach(function (element, index, array) {               
             //   if (element.CURRENCY_CODE != '')
            // if (currencyCodes.findIndex(function (element, index, array) { return this === element.CODE; }, element.CURRENCY_CODE) == -1)
            //      currencyCodes.push({ "CODE": item });
            // });

            var categoryNames = self.groupBy(self.contractsCollection, 'CURRENCY_CODE');
            $.each(categoryNames, function (index, item) {
                currencyCodes.push({ "CODE": item });
            });

           // console.log(JSON.stringify(currencyCodes));

            if (currencyCodes.length > 1) {
                var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'templates/newquoteparams.html',
                    controller: 'NewQuoteParamsController',
                    size: 'sm'
                });

                modalInstance.result.then(function (currencyCode) {
                    if (currencyCode) {                       
                        CommonServices.newQuoteParamsObj.ContractIDs = self.contractsCollection;
                        if (self.leadContract) CommonServices.newQuoteParamsObj.LeadContract = self.leadContract;
                        if (self.selectedAccount) CommonServices.newQuoteParamsObj.OppID = self.selectedAccount.OppID;
                        CommonServices.newQuoteParamsObj.Currency = currencyCode;
                        
                       // CommonServices.currencyParam = currencyCode;
                        $location.path("/createQuote");
                    }

                }, function () {
                    //console.log('Modal dismissed at: ' + new Date());
                });
            }
            else {               
                CommonServices.newQuoteParamsObj.ContractIDs = self.contractsCollection;
                if (self.leadContract) CommonServices.newQuoteParamsObj.LeadContract = self.leadContract;
                if (self.selectedAccount) CommonServices.newQuoteParamsObj.OppID = self.selectedAccount.OppID;
                CommonServices.newQuoteParamsObj.Currency = currencyCodes[0].CODE;

                $location.path("/createQuote");
            }
        };


        //initialize search fields and options
        self.init();



        //********************* Select Contracts functions ************************************************************
        //self.showTab = function(_tab){
        //    angular.element("#tableTabs .active").removeClass("active");
        //    self.currentTab = _tab;
        //    angular.element("#tab"+_tab).addClass("active");
        //};
        self.check = 'NO';
        self.selectAll = function selectAll(checked) {
                for (var i = 0; i < self.contractsCollection.length; i++) {
                    var selectedRow = self.contractsCollection[i];
                        self.contractsCollection[i].isSelected = checked;                        
                }
            };

        self.selectRow = function selectRow(row, mode) {
                var index = self.displayContractsCollection.indexOf(row);//self.contractsCollection.indexOf(row);
                var selectedRow = self.displayContractsCollection[index];//self.contractsCollection[index];
            if (index !== -1) {
                    //self.contractsCollection[index]
                    self.displayContractsCollection[index].isSelected = !selectedRow.isSelected;
                }
        };

        self.getSelectedRows = function () {
            var selectedItems = [];
            for (var i = 0; i < self.contractsCollection.length; i++) {
                if (self.contractsCollection[i].isSelected) {
                    selectedItems.push(self.contractsCollection[i]);
                }
            }

            return selectedItems;
        };

        self.removeSelectedRows = function () {
            //Get Selected Rows
            var selectedRows = self.getSelectedRows();
            //Remove Each Selcetd Row
            for (var i = 0; i < selectedRows.length; i++) {
                self.removeItem(selectedRows[i]);
            }
        };

        //remove to the real data holder
        self.removeItem = function removeItem(row) {
            var index = self.contractsCollection.indexOf(row);
            if (index !== -1) {
                self.contractsCollection.splice(index, 1);
            }
        };

            //initialize exp. perion field options and set default value
            self.pagingVal = {
                options: [
                  { id: '5', name: '5 items' },
                  { id: '25', name: '25 items' },
                  { id: '50', name: '50 items' },
                  { id: '75', name: '75 items' },
                  { id: '100', name: '100 items' }
                ]
            };
            //Default value for select paging
            self.pagingVal.selectedOption = self.pagingVal.options[0];
            //Default number of values forpaging
            self.itemsByPage = self.pagingVal.options[0].id;

            self.changeNumberOfItemsInPage = function changeNumberOfItemsInPage(value) {
                self.itemsByPage = value;
            };

            self.groupBy = function (items, propertyName) {
                var result = [];
                $.each(items, function (index, item) {
                    if ($.inArray(item[propertyName], result) == -1) {
                        result.push(item[propertyName]);
                    }
                });
                return result;
            }
    }]);
